package org.xlh.springboot.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xlh.springboot.bean.Account;
import org.xlh.springboot.exception.TransferException;
import org.xlh.springboot.repository.AccountMapper;
import org.xlh.springboot.service.AccountService;

@Transactional
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void transfer(String fromActNo, String toActNo, double money) {
        //转账的业务逻辑
        //判断转出账户的余额是否足够
        Account fromAct = accountMapper.selectByActNo(fromActNo);
        if (fromAct.getBalance() < money) {
            throw new TransferException("余额不足");
        }
        Account toAct = accountMapper.selectByActNo(toActNo);

        fromAct.setBalance(fromAct.getBalance() - money);
        toAct.setBalance(toAct.getBalance() + money);

        //更新账户余额
        int count = accountMapper.updateByActNo(fromAct);

        //模拟异常
//        if(1 == 1)
//        {
//            throw new TransferException("转账失败");
//        }

        count += accountMapper.updateByActNo(toAct);

        if (count != 2) {
            throw new TransferException("转账失败");
        }
    }
}
